using System;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GoChat_for_Windows.Services;
using GoChat_for_Windows.Views;

namespace GoChat_for_Windows.ViewModels
{
    public partial class LoginViewModel : ViewModelBase
    {
        private readonly INavigationService _navigationService;
        private readonly ILocalStorageService _localStorageService;

        [ObservableProperty]
        private string username = string.Empty;

        [ObservableProperty]
        private string password = string.Empty;

        [ObservableProperty]
        private bool rememberMe;

        public LoginViewModel(
            IApiService apiService,
            INavigationService navigationService,
            ILocalStorageService localStorageService) : base(apiService)
        {
            _navigationService = navigationService;
            _localStorageService = localStorageService;
        }

        [RelayCommand]
        private async Task LoginAsync()
        {
            if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password))
            {
                ErrorMessage = "用户名和密码不能为空";
                return;
            }

            try
            {
                IsBusy = true;
                ClearError();

                var user = await ApiService.LoginAsync(Username, Password);
                if (user != null)
                {
                    // 保存用户信息到本地
                    await _localStorageService.SaveUserAsync(user);
                    // 导航到主页面
                    _navigationService.Navigate(typeof(MainPage));
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "登录失败：" + ex.Message;
            }
            finally
            {
                IsBusy = false;
            }
        }

        [RelayCommand]
        private void NavigateToRegister()
        {
            _navigationService.Navigate(typeof(RegisterPage));
        }
    }
} 